// src\views\sendbox\new-manage\NewsUpdate.jsx
// 新闻更新
import React, { useState, useRef, useEffect } from 'react'
import { Steps, Button, message, Form, Input, Select, Space,notification } from 'antd'
// 引入样式
import style from './NewsAdd.module.css';
import axios from 'axios';
import NewsEditor from "@/components/News/NewsEditor"
export default function NewsUpdate(props) {
  const steps = [
    {
      title: '基本信息',
      content: '新闻标题，新闻分类',
    },
    {
      title: '新闻内容',
      content: '新闻主体内容',
    },
    {
      title: '新闻提交',
      content: '保存草稿或者提交审核',
    },
  ];
  const { Option } = Select;
  const [NewForm, setNewForm] = useState({});
  const [current, setCurrent] = useState(0);
  const NewsForm = useRef(null)
  const Layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }
  const User=JSON.parse(localStorage.getItem('token'));
  useEffect(()=>{
    axios.get(`http://localhost:8888/news/${props.match.params.id}?_expand=category&_expand=role`).then(res=>{
      let {title,categoryId,content}=res.data;
      NewsForm.current.setFieldsValue({
        title,categoryId
      });
      setContent(content);
    })
  },[props.match.params]);
  // 新闻分类
  const [categoryList, setCategoryList] = useState([]);
  useEffect(() => {
    axios.get('http://localhost:8888/categories').then(res => {
      setCategoryList(res.data);
    })
  }, []);
  const [content, setContent] = useState("")
// 下一步
  const next = () => {
    if (current === 0) {
      NewsForm.current.validateFields().then(res => {
        setNewForm(res);
        setCurrent(current + 1);
      }).catch(err => console.log(err));
    } else if (current === 1) {
      if (content === "" || content.trim() === '<p></p>') {
        message.warning('新闻内容请勿为空');
      } else {
        setCurrent(current + 1);
      }
    } else {
      setCurrent(current + 1);
    }
  };
  // 保存草稿或是提交审核
  const handleSave=(editState)=>{
    console.log(NewForm);
    axios.post('http://localhost:8888/news',{
      ...NewForm,
      content,
      region:User.region?User.region:"全球",
      author:User.username,
      roleId:User.roleId,
      auditState:editState,
      publishState:0,
      createTime:Date.now(),
      star:0,
      view:0
    }).then(res=>{
      notification.info({
        message:'通知',
        description:`您可以到${editState===0?'草稿箱':'审核列表'}中查看您的新闻`,
        placement:"bottomRight"
      })
      props.history.push(editState===0?'/news-manage/draft':'/audit-manage/list');
    })
  }
  const prev = () => {
    setCurrent(current - 1);
  };
  const items = steps.map((item) => ({
    key: item.title,
    title: item.title,
  }));

  return (
    <div>
      <Steps current={current} items={items} />
      <div style={{ marginTop: "50px" }}>
        <div className={current === 0 ? "" : style.active}>
          <Form {...Layout}
            ref={NewsForm}>
            <Form.Item
              label='新闻标题'
              name='title'
              rules={[{ required: true, message: '请输入新闻标题' }]}
            >
              <Input></Input>
            </Form.Item>
            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[{ required: true, message: "请选择分类" }]}
            >
              <Select>
                {
                  categoryList.map(e => {
                    return <Option value={e.id} key={e.id}>{e.title}</Option>
                  })
                }
              </Select>
            </Form.Item>
          </Form>
        </div>
        <div className={current === 1 ? "" : style.active}>
          <NewsEditor
            content={content}
            getContent={(value) => { setContent(value); console.log("content", content); }}
          />

        </div>

      </div>
      {/* 底部 */}
      <div
        style={{
          marginTop: 24,
        }}
      >
        {current === 2 && (
          <Space>
            <Button type="primary" onClick={() => handleSave(0)}>
              保存到草稿箱
            </Button>
            <Button type="primary" onClick={() => handleSave(1)}>
              提交审核
            </Button>
          </Space>
        )}
        {current < 2 && (

          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current > 0 && (
          <Button
            style={{
              margin: '0 8px',
            }}
            onClick={() => prev()}
          >
            上一步
          </Button>
        )}
      </div>


    </div >
  )
}
